class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target)
    {
        vector<vector<int>> ret;
        sort(nums.begin(), nums.end());
        int n = nums.size();
        int fast = 0;
        while (fast < n - 3)
        {
            int key = fast + 1;
            while (key < n - 2)
            {
                int left = key + 1, right = n - 1;
                while (left < right)
                {

                    long long sum = (long long)nums[left] + nums[right] + nums[key] + nums[fast];
                    if (sum > target)
                        right--;
                    else if (sum < target)
                        left++;
                    else
                    {

                        if (nums[left] == nums[left + 1])
                            while (left < right && nums[left + 1] == nums[left])
                                left++;
                        if (nums[right] == nums[right - 1])
                            while (left < right && nums[right - 1] == nums[right])
                                right--;
                        ret.push_back({ nums[fast],nums[key],
                                  nums[left], nums[right] });
                        left++;
                        right--;
                    }
                }
                while (key + 1 < n - 2 && nums[key] == nums[key + 1]) key++;
                key++;
            }
            if (nums[fast] == nums[fast + 1] && key < n)
                while (fast + 1 < n && nums[fast] == nums[fast + 1])
                    fast++;
            fast++;
        }
        return ret;
    }

};